//
//  OrderStateVC.swift
//  Employee
//
//  Created by swordjoy on 2017/3/24.
//  Copyright © 2017年 remotevillage. All rights reserved.
//

import UIKit
import SwiftyJSON
import MJRefresh
import Moya

enum OrderStateVCType {
    case all
    case timeOut
    case accepting
    case submit
    case wait
}

class OrderStateVC: BaseVC {
    var parentVC: UIViewController!
    var type: OrderStateVCType!

    fileprivate var noDataV: NoDataV?
    fileprivate var workOrders: [WorkOrder] = []
    fileprivate var page = PageModel()
    fileprivate var tableView: UITableView!
    fileprivate var headerCancle: Cancellable?

    override func viewDidLoad() {
    super.viewDidLoad()
        view.backgroundColor = GlobalConfig.BGWhiteColor

        create()
    }
  
}

// MARK: - interface 

extension OrderStateVC {
    /// 外面第一次进来刷新数据
    func updateData() {
        headerRefresh()
    }
  
    func dismiss() {
        headerCancle?.cancel()
        tableView.mj_header.endRefreshing()
    }
}

// MARK: - fileprivate

extension OrderStateVC {
  
    fileprivate func noData() {
        let frame = CGRect(x: 0, y: 0, width: UIScreen.width, height: UIScreen.noBarHeight)
        noDataV = NoDataV(frame: frame)
        noDataV?.image = UIImage(named: "bg-01")!

        var typeString = ""

        if .all == type { typeString = "暂无全部工单"}
        else if .accepting == type { typeString = "暂无受理工单" }
        else if .submit == type { typeString = "暂无提交工单" }
        else if .wait == type { typeString = "暂无待接工单" }
        noDataV?.topTipText = typeString
        if let tempV = noDataV { self.tableView.addSubview(tempV) }
    }
  
  // 最后一个table footer改变
  fileprivate func lastPage() {
  
    tableView.mj_footer.isHidden = true
    
  }
  
  @objc fileprivate func headerRefresh() {
    
    var typeString = ""
    
    if .all == type {
      typeString = "all"
    } else if .accepting == type {
      typeString = "accepted"
    } else if .submit == type {
      typeString = "commited"
    } else if .wait == type {
      typeString = "untreated"
    }
    
    headerCancle = WorkorderRequest.shared.getOrder(status: typeString, pagepn: page.headerPage, success: { (orders, pageModel) in
      
      self.tableView.mj_header.endRefreshing()
      
      if orders.isEmpty {
        self.noData()
        return
      } else {
        if let _ = self.noDataV?.superview { self.noDataV?.removeFromSuperview() }
      }
      
      self.workOrders = orders
      self.page = pageModel
      
      self.tableView.reloadData()
      
      self.tableView.mj_footer.isHidden = false
      // 分页判断
      if !self.page.hasNextPage { self.lastPage() }
      
    }, failure: { 
      
      self.tableView.mj_header.endRefreshing()
      
    })
    
    
  }
  
  @objc fileprivate func footerRefresh() {
    
    var typeString = ""
    
    if .all == type {
      typeString = "all"
    } else if .accepting == type {
      typeString = "accepted"
    } else if .submit == type {
      typeString = "commited"
    } else if .wait == type {
      typeString = "untreated"
    }
    
    let _ = WorkorderRequest.shared.getOrder(status: typeString, pagepn: page.nextPage, success: { (orders, pageModel) in
      
      self.workOrders += orders
      self.page = pageModel
      
      self.tableView.mj_footer.isHidden = false
      // 分页判断
      if !self.page.hasNextPage {
        self.lastPage()
      } else {
        self.tableView.mj_footer.endRefreshing()
      }
      
      self.tableView.reloadData()
      
    }) { 
      self.tableView.mj_footer.endRefreshing()
    }
    
  }
  
  fileprivate func create() {
    
    tableView = UITableView()
    tableView.backgroundColor = GlobalConfig.BGWhiteColor
    tableView.frame = CGRect(x: 0, y: 0, width: UIScreen.width, height: UIScreen.noNavBarHeight - 44.0)
    tableView.delegate = self
    tableView.dataSource = self
    tableView.separatorStyle = .none
    tableView.register(WorkOrderCell.self, forCellReuseIdentifier: WorkOrderCell.identifier)
    
    let footerView = UIView(frame: CGRect(x: 0, y: 0, width: UIScreen.width, height: 10))
    footerView.backgroundColor = GlobalConfig.BGWhiteColor
    tableView.tableFooterView = footerView
    
    let headerView = UIView(frame: CGRect(x: 0, y: 0, width: UIScreen.width, height: 4))
    headerView.backgroundColor = GlobalConfig.BGWhiteColor
    tableView.tableHeaderView = headerView
    
    tableView.mj_header = CustomRefreshHeader(refreshingTarget: self, refreshingAction: #selector(headerRefresh))
    tableView.mj_footer = MJRefreshAutoNormalFooter(refreshingTarget: self, refreshingAction: #selector(footerRefresh))
    tableView.mj_footer.isHidden = true
    
    view.addSubview(tableView)
    
  }
  
}

// MARK: - UITableViewDataSource

extension OrderStateVC : UITableViewDataSource {
  
  func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
    
    return workOrders.count
    
  }
  
  func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
    
    let cell = tableView.dequeueReusableCell(withIdentifier: WorkOrderCell.identifier) as! WorkOrderCell
    cell.model = workOrders[indexPath.row]
    return cell
    
  }
  
}

// MARK: - UITableViewDelegate

extension OrderStateVC : UITableViewDelegate {
  
  func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
    return WorkOrderCell.height(with: workOrders[indexPath.row])
  }
  
  func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
    
    let vc = OrderDetailBaseVC()
    vc.orderId = workOrders[indexPath.row].id
    vc.parentVC = parentVC
    vc.orderStatus = OrderHelper.getType(order: workOrders[indexPath.row])
    parentVC.navigationController?.pushViewController(vc, animated: true)
    
  }
  
  func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {
    
    let fixView = UIView(frame: CGRect(x: 0, y: 0, width: UIScreen.width, height: 1))
    fixView.backgroundColor = GlobalConfig.BGWhiteColor
    return fixView
    
  }
  
  func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat {
    return 1
  }
  
}
